<?php
/**
 * 名称：GlobalAction
 * 描述：全局设置
 * 作者：lan 时间：2013-05-02
 * 版本号：V1.0.0
 * ========================历史版本=================================
 * 序号	 版本号 	日期			姓名	 	描述
 * 1 	V1.0.0 	2013-05-02 	lan  	全局设置
 * ========================历史版本=================================
 * 说明：请在有更改程序的时候修改以上注释
 */
class GlobalAction extends CommonAction {
	
	/**
	 * 请求验证
	 * @param unknown_type $field
	 * @param unknown_type $array
	 * @return boolean
	 */
	private function __isValidRequest($field, $array = 'post') {
        $field = is_array($field) ? $field : explode(',', $field);
        $array = $array == 'post' ? $_POST : $_GET;
        foreach ($field as $v){
            $v = trim($v);
            if ( !isset($array[$v]) || $array[$v] == '' ) return false;
        }
        return true;
    }

    /**
     * 系统配置 - 站点配置
     * Create Data <2013-05-02>
     */
    public function siteopt() {
    	$siteopt = model('Data')->lget('siteopt');
    	if(empty($siteopt['languageselect'])) {
    		$siteopt['languageselect'] = 'zh-cn';
    	}
        $this->assign($siteopt);
        $list = M('system_data')->where("list='siteopt' ")->select();

        for($k=0;$k<count($list);$k++) {
        	if($list[$k]["key"]=="statcode"){
        		$statcode=common('String')->unserialize_plus($list[$k]["value"]);
        		$statcode = base64_decode($statcode);
        		$statcode=str_replace('\"','"',$statcode);
        		$statcode=str_replace("\'","'",$statcode);
        		$this->assign("statcode",$statcode);
        		continue;
        	}
        }
        $this->display();
    }

    /**
     * 设置站点
     * Create Data <2013-05-02>
     */
    public function doSetSiteOpt() {
    	if (empty($_POST)) {
    		$this->error(L('parameterError'));//参数错误
    	}
    	$LOG['uid'] = $this->mid;
    	$LOG['type'] = '3';
    	$data[] = L("global")."-".L("siteConfig");//'全局配置 - 站点配置 ';
    	$d = model('Data')->lget('siteopt');
    	$data[] = $d;
    	if(isset($_POST['statcode'])){
    		$_POST['statcode'] = base64_encode($_POST['statcode']);
    	}
    	$data[] = $_POST;
    	$LOG['data'] = serialize($data);
    	$LOG['ctime'] = time();
    	M('AdminLog')->add($LOG);
    	$result = model('Data')->lput('siteopt', $_POST);
    	if($result) {
    		if(isset($d['languageselect']) && $d['languageselect'] == $_POST['languageselect']) {
    			$this->success(L('saveSuccess'));//保存成功
    		} else {
	    		$url = URL('admin/Index/index',array('l'=>$_POST['languageselect']));
	    		echo '<script>parent.location.href="'.$url.'";</script>';
	    		A('Index')->cleanRuntime2();
    		}
    	} else {
    		$this->error(L('saveFails'));//保存失败
    	}
    }

    /**
     * 系统配置 - SEO配置
     * Create Data <2013-05-02>
     */
    public function siteseo() {
    	// URL静态化
        $UrlStatic = M('UrlStatic');
        $data = $UrlStatic->order('id ASC')->select();
        $this->assign($data);
        // 门户
        $siteseo = model('Data')->lget('siteseo');
        $this->assign($siteseo);

        $this->display('portal');
    }

    /**
     * URL静态化
     * Create Data <2013-05-02>
     */
    public function urlStatic() {
		$data = model('Data')->lget('siteseo');
    	$this->assign($data);
        $this->display();
    }

    /**
     * 门户
     * Create Data <2013-05-02>
     */
    public function portal() {
        $data = model('Data')->lget('siteseo');
        $this->assign($data);
        $this->display();
    }

    /**
     * Rewrite规则
     * Create Data <2013-05-02>
     */
    public function rewrite() {
    	$software = $_SERVER ["SERVER_SOFTWARE"];
    	$server = explode("/",$software);
    	$server_software = $server[0];
    	if (strtolower($server_software) === "apache"){
    		$filename = "./URLRewrite/.htaccess";
    	} else if(strtolower($server_software) === "nginx"){
    		$filename = "./URLRewrite/nginx.conf";
    	} else {
    		$filename = "./URLRewrite/httpd.ini";
    	}
    	$this->assign('server_software',$server_software);
    	$this->assign('contents',$this->readFileContent($filename));
        $this->display();
    }

    /**
     * 全部Rewrite规则
     * Create Data <2013-10-15>
     */
    public function moreRewrite() {
    	$this->assign('apache',$this->readFileContent("./URLRewrite/.htaccess"));
    	$this->assign('nginx',$this->readFileContent("./URLRewrite/nginx.conf"));
    	$this->assign('httpd',$this->readFileContent("./URLRewrite/httpd.ini"));
    	$this->display();
    }

    /**
     * 读取文件内容
     * @param unknown_type $filename
     * @return unknown
     */
    private function readFileContent($filename){
    	if(file_exists($filename)) {
    		$handle = fopen($filename, "r");
    		$contents = fread($handle, filesize ($filename));
    		fclose($handle);
    	}
    	return $contents;
    }

    /**
     * 设置SEO
     * Create Data <2013-05-02>
     */
    public function doSetSeo() {
    	if (empty($_POST)) {
    		$this->error(L('parameterError'));//参数错误
    	}
    	$LOG['uid'] = $this->mid;
    	$LOG['type'] = '3';
    	$data[] = L("global")."-".L("seoConfig");//'全局配置 - SEO配置 ';
    	$data[] = model('Data')->lget('siteseo');
    	$data[] = $_POST;
    	$LOG['data'] = serialize($data);
    	$LOG['ctime'] = time();
    	M('AdminLog')->add($LOG);
    	$result = model('Data')->lput('siteseo', $_POST);
    	if($result) {
    		$this->success(L('saveSuccess'));//保存成功
    	} else {
    		$this->error(L('saveFails'));//保存失败
    	}
    }

    /**
     * 设置URL静态化
     * Create Data <2013-05-02>
     */
    public function doSetUrlStatic() {
    	if( $_POST['__hash__'] )unset( $_POST['__hash__'] );
    	$result = model('Data')->lput('siteseo',$_POST);
    	if($result) {
    		$this->success(L('saveSuccess'));//保存成功
    		A('Index')->cleanRuntime2();
    	} else {
    		$this->error(L('saveFails'));//保存失败
    	}
    }

    /**
     * 系统配置 - 域名配置
     * Create Data <2013-05-02>
     */
    public function domain() {
        $domain = model('Data')->lget('domain');
        $this->assign($domain);
    	$this->display();
    }

    /**
     * 设置站点
     * Create Data <2013-05-02>
     */
    public function doSetDomain() {
    	if (empty($_POST)) {
    		$this->error(L('parameterError'));//参数错误
    	}
    	$LOG['uid'] = $this->mid;
    	$LOG['type'] = '3';
    	$data[] = L("global")."-".L("domainConfig");//'全局配置 - 域名配置 ';
    	$data[] = model('Data')->lget('domain');
    	$data[] = $_POST;
    	$LOG['data'] = serialize($data);
    	$LOG['ctime'] = time();
    	M('AdminLog')->add($LOG);
    	$result = model('Data')->lput('domain', $_POST);
    	if($result) {
    		$this->success(L('saveSuccess'));//保存成功
    	} else {
    		$this->error(L('saveFails'));//保存失败
    	}
    }

    /**
     * 系统配置 - 注册配置
     * Create Data <2013-05-02>
     */
    public function register() {
        $register = model('Data')->lget('register');
        $this->assign($register);
        $this->display();
    }

	/**
	 * 注册配置存档
	 * Create Data <2013-05-02>
	 */
	public function doSetRegisterOpt() {
		$_LOG ['uid'] = $this->mid;
		$_LOG ['type'] = '3';
		$data [] = L ( "global" ) . "-" . L ( "registerConfig" ); // '全局配置 - 注册配置 ';
		$data [] = model ( 'Data' )->lget ( 'register' );
		if ($_POST ['__hash__'])
			unset ( $_POST ['__hash__'] );
		$data [] = $_POST;
		$_LOG ['data'] = serialize ( $data );
		$_LOG ['ctime'] = time ();
		M ( 'AdminLog' )->add ( $_LOG );

		unset ( $_POST ['__hash__'] );
		$_POST ['settingnew'] ['bbrulestxt'] = common ( 'Html' )->safeHtml ( $_POST ['settingnew'] ['bbrulestxt'] );

		$type=$_POST['send_type'];
		$user=model('User');
		if($type=="0") {
			$uid=$_POST['send_type_user'];
			$ulist[]=explode(",",$uid);
			$i=0;
			for($j=0;$j<count($ulist[0]);$j++) {
				if($ulist[0][$j].trim()!=""){
					$list[$i]["uid"]=$ulist[0][$j];
					$i++;
				}
			}
		}else {
			$list = model('User')->field("uid")->select();
		}
		$db_prefix  = C('DB_PREFIX');
		$num=$_POST['send_type_num'];
		$insert_sql	=	"INSERT INTO ".$db_prefix."invitecode (uid,code,is_used) VALUES ";
		for ($i=1;$i<=$num;$i++){
			for($k=0;$k<count($list);$k++) {
				$invitecode = md5($uid.time()."^@*&@*HF*@&#&@*(*@#".$i.$k);
				$insert_sql=$insert_sql."(".$list[$k]["uid"].",'".$invitecode."',0),";
			}
		}
		$insert_sql	=	rtrim($insert_sql,',');
		//插入数据列表
		$cd = M('invitecode');
		$cd->query($insert_sql);
		$result = model ( 'Data' )->lput ( 'register', $_POST );
		if ($result) {
			$this->success ( L ( 'saveSuccess' ) ); // 保存成功
		} else {
			$this->error ( L ( 'saveFails' ) ); // 保存失败
		}
	}

	/**
     * 系统配置 - 防灌水配置
     * Create Data <2013-05-02>
     */
    public function guanshui() {
        $guanshui = model('Data')->lget('guanshui');
        $this->assign($guanshui);
    	$this->display();
    }

    /**
     * 防灌水配置－保存
     * Create Data <2013-05-02>
     */
    public function doSetGuanshui() {
    	if (empty($_POST)) {
    		$this->error(L('parameterError'));//参数错误
    	}
    	$LOG['uid'] = $this->mid;
    	$LOG['type'] = '3';
    	$data[] = L("global")."-".L("guanshuiConfig");// '全局配置 - 防灌水配置 ';
    	$data[] = model('Data')->lget('guanshui');
    	$data[] = $_POST;
    	$LOG['data'] = serialize($data);
    	$LOG['ctime'] = time();
    	M('AdminLog')->add($LOG);
    	$result = model('Data')->lput('guanshui', $_POST);
    	if($result) {
    		$this->success(L('saveSuccess'));//保存成功
    	} else {
    		$this->error(L('saveFails'));//保存失败
    	}
    }


    /**
     * 系统配置 - 积分配置
     * Create Data <2013-05-02>
     */
    public function credit() {
        $list = M('credit_setting')->order('id ASC')->select();
        $creditType = M('credit_type')->order('id ASC')->select();
        $this->assign('creditType',$creditType);
        $this->assign('list',$list);
    	$this->display();
    }

    /**
     * 添加积分规则
     * Create Data <2013-05-02>
     */
    public function addCredit() {
        $creditType = M('credit_type')->order('id ASC')->select();//积分类别
        $this->assign('creditType',$creditType);
        $this->assign('type','add');
        $this->display('editCredit');
    }

    /**
     * 编辑积分规则
     * Create Data <2013-05-02>
     */
    public function editCredit() {
        $cid    = $_GET['id'];
        $credit = M('credit_setting')->where("id=".$cid)->find();
        $this->assign('credit', $credit);

        $creditType = M('credit_type')->order('id ASC')->select();//积分类别
        $this->assign('creditType',$creditType);

        $this->assign('type', 'edit');
        $this->display();
    }

    /**
     * 添加积分规则-保存
     * Create Data <2013-05-02>
     */
    public function doAddCredit() {
    	$name = trim($_POST['name']);
    	if($name == ""){
    		$this->error(L("nameNotNull"));//名称不能为空
    	}
    	$credit=M("credit_setting");
    	$credit_id = $credit->max('id');
        $credit_id=$credit_id+1;
    	$list = $credit->where("name='".$name."'")->select();
    	if(count($list)>0)
    		$this->error(L("Name").L("having"));//'名称已经存在'
    	$db_prefix  = C('DB_PREFIX');
    	//组装积分规则
    	$creditTypeDao = M('credit_type');
    	$creditType = $creditTypeDao->select();
    	$db_prefix  = C('DB_PREFIX');
    	$ins_sql="INSERT INTO ".$db_prefix."credit_setting(id,name,alias,type";
    	$ins_val="values(".$credit_id.",'".$name."','".$_POST['alias']."','".$_POST['type']."'";
    	foreach($creditType as $v){
    		if(!is_numeric($_POST[$v['name']]))
    			$this->error($v['alias'].L("mstIsNumber"));//的值必须为数字！
    		//$value[$v['name']] = intval($_POST[$v['name']]);
    		$ins_sql=$ins_sql.",".$v['name'];
    		$ins_val=$ins_val.",".$_POST[$v['name']];
    	}
    	$ins_sql=$ins_sql.")".$ins_val.")";
    	$_LOG['uid'] = $this->mid;
    	$_LOG['type'] = '1';
    	$data[] = L("global")."-".L("creditConfig")."-".L("creditRule");//全局 - 积分配置 - 积分规则
    	if( $_POST['__hash__'] )unset( $_POST['__hash__'] );
    	$data[] = $_POST;
    	$_LOG['data'] = serialize($data);
    	$_LOG['ctime'] = time();
    	M('AdminLog')->add($_LOG);

    	$res=$credit->query($ins_sql);
    	if (count($res)==0) {
    		// 清缓存
    		F('_service_credit_rules', null);
    		$this->assign('jumpUrl', URL('admin/Global/credit'));
    		$this->success(L('saveSuccess'));//保存成功
    	}else {
    		$this->error(L('saveFails'));//保存失败
    	}
    }

    /**
     * 编辑积分规则－保存
     * Create Data <2013-05-02>
     */
    public function doEditCredit() {
    	$name = trim($_POST['name']);
    	if($name == ""){
    		$this->error(L("nameNotNull"));//名称不能为空
    	}
    	$id=$_POST['id'];
    	$credit = M('credit_setting');
    	$list = $credit->where("name='".$name."' AND id<>".$id)->select();
    	if(count($list)>0)
    		$this->error(L("Name").L("having"));//'名称已经存在'
    	//组装积分规则
    	$db_prefix  = C('DB_PREFIX');
    	$creditTypeDao = M('credit_type');
    	$creditType = $creditTypeDao->select();
    	$upd_sql="UPDATE ".$db_prefix."credit_setting SET name='".$name."',";
    	$upd_sql=$upd_sql."alias='".$_POST['alias']."',type='".$_POST['type']."'";
    	foreach($creditType as $v){
    		if(!is_numeric($_POST[$v['name']]))
    			$this->error($v['alias'].L("mstIsNumber"));//的值必须为数字！
    		//$value[$v['name']] = intval($_POST[$v['name']]);
    		$upd_sql=$upd_sql.",".$v['name']."=".$_POST[$v['name']];
    	}
    	$upd_sql=$upd_sql." WHERE id=".$id;

    	$_LOG['uid'] = $this->mid;
    	$_LOG['type'] = '3';
    	$data[] = L("global")."-".L("creditConfig")."-".L("creditRule");//全局 - 积分配置 - 积分规则
    	if( $_POST['__hash__'] )unset( $_POST['__hash__'] );
    	$data[] = $_POST;
    	$_LOG['data'] = serialize($data);
    	$_LOG['ctime'] = time();
    	M('AdminLog')->add($_LOG);

    	$res = $credit->query($upd_sql);
    	if (count($res)==0) {
    		// 清缓存
    		F('_service_credit_rules', null);
    		$this->assign('jumpUrl', URL('admin/Global/credit'));
    		$this->success(L('saveSuccess'));//保存成功
    	}else {
    		$this->error(L('saveFails'));//保存失败
    	}
    }

    /**
     * 积分规则－删除
     * Create Data <2013-05-02>
     */
    public function doDeleteCredit(){
    	$ids = $_POST['ids'];
    	if ( empty($ids) ) {echo 0; return ;}

    	$credit = M('credit_setting');
    	$_LOG['uid'] = $this->mid;
    	$_LOG['type'] = '2';
    	$data[] = L("global")."-".L("creditConfig")."-".L("creditRule");//'全局 - 积分配置 - 积分规则 ';
    	$_LOG['data'] = serialize($data);
    	$_LOG['ctime'] = time();
    	M('AdminLog')->add($_LOG);

    	//清除type信息和对应字段
    	$res = $credit->where("id in(".$ids.")")->delete();
    	if ($res){
    		F('_service_credit_type', null);// 清缓存
    		echo 1;
    	}else{
    		echo 0;
    	}
    }

    /**
     * 系统配置 - 积分类型
     * Create Data <2013-05-02>
     */
    public function creditType() {
    	$creditType = M('credit_type')->order('id ASC')->select();
        $this->assign('list',$creditType);
        $this->display();
    }

    /**
     * 系统配置 - 站点配置
     * Create Data <2013-05-02>
     */
    public function addCreditType() {
    	$this->assign('type', 'add');
    	$this->display("editCreditType");
    }

    /**
     * 系统配置 - 站点配置
     * Create Data <2013-05-02>
     */
    public function editCreditType(){
    	$cid = $_GET['id'];
    	$creditType = M('credit_type')->where("`id`=$cid")->find();//积分类别
    	$this->assign('creditType',$creditType);
    	$this->assign('type', "edit");
    	$this->display();
    }

    /**
     * 系统配置 - 站点配置
     * Create Data <2013-05-02>
     */
    public function doAddCreditType(){
    	$name = $_POST['name'];
    	$alias=$_POST['alias'];
    	if(empty($name) ){
    		$this->error(L("Name").L("notNull"));//名称不能为空
    	}
    	if(empty($alias) ){
    		$this->error(L("alias").L("notNull"));//别名不能为空
    	}
    	$list = M('credit_type')->where("name='".$name."'")->select();
    	if(count($list)>0)
    		$this->error(L("Name").L("having"));//'名称已经存在'

    	$_LOG['uid'] = $this->mid;
    	$_LOG['type'] = '1';
    	$data[] = L("global")."-".L("creditConfig")."-".L("creditType");//'全局 - 积分配置  - 积分类型';
    	if( $_POST['__hash__'] )unset( $_POST['__hash__'] );
    	$data[] = $_POST;
    	$_LOG['data'] = serialize($data);
    	$_LOG['ctime'] = time();
    	M('AdminLog')->add($_LOG);
    	$value["name"]=$name;
    	$value["alias"]=$alias;
    	$res = M('credit_type')->data($value)->add();
    	if ($res) {
            $db_prefix  = C('DB_PREFIX');
            $model = M('');
            $setting = $model->query("ALTER TABLE {$db_prefix}credit_setting ADD {$_POST['name']} INT(11) DEFAULT 0;");
            $user    = $model->query("ALTER TABLE {$db_prefix}credit_user ADD {$_POST['name']} INT(11) DEFAULT 0;");
			// 清缓存
    		F('_service_credit_type', null);
    		$this->assign('jumpUrl', URL('admin/Global/creditType'));
    		$this->success(L('saveSuccess'));//保存成功
    	}else {
    		$this->error(L('saveFails'));//保存失败
    	}
    }

    /**
     * 编辑积分类别－保存
     * Create Data <2013-05-02>
     */
    public function doEditCreditType(){
    	$name = $_POST['name'];
    	$alias= $_POST['alias'];
    	$id=$_POST['id'];
    	if(empty($name) ){
    		$this->error(L("Name").L("notNull"));//名称不能为空
    	}
    	if(empty($alias) ){
    		$this->error(L("alias").L("notNull"));//别名不能为空
    	}
    	$creditTypeDao = M('credit_type');
    	$list = $creditTypeDao->where("name='".$name."' AND id<>".$id)->select();
    	if(count($list)>0)
    		$this->error(L("Name").L("having"));//'名称已经存在'

    	$_LOG['uid'] = $this->mid;
    	$_LOG['type'] = '3';
    	$data[] = L("global")."-".L("creditConfig")."-".L("creditType");//'全局 - 积分配置 - 积分类型 ';
    	$data[] = $oldName;
    	//获取原字段名
    	$oldName = $creditTypeDao->find($id);
    	$data[]=$oldName;
    	if( $_POST['__hash__'] )unset( $_POST['__hash__'] );
    	$data[] = $_POST;
    	$_LOG['data'] = serialize($data);
    	$_LOG['ctime'] = time();
    	M('AdminLog')->add($_LOG);

    	//修改字段名
    	$res = $creditTypeDao->save($_POST);

    	if ($res) {
            $db_prefix  = C('DB_PREFIX');
            $model = M('');
            $setting = $model->query("ALTER TABLE {$db_prefix}credit_setting CHANGE {$oldName['name']} {$name} INT(11) DEFAULT 0;");
            $user    = $model->query("ALTER TABLE {$db_prefix}credit_user CHANGE {$oldName['name']} {$name} INT(11) DEFAULT 0;");
			// 清缓存
    		F('_service_credit_type', null);
    		$this->assign('jumpUrl', URL('admin/Global/creditType'));
    		$this->success(L('saveSuccess'));//保存成功
    	}else {
    		$this->error(L('saveFails'));//保存失败
    	}
    }

    /**
     * 积分类别－删除
     * Create Data <2013-05-02>
     */
    public function doDeleteCreditType(){
    	$ids = $_POST['ids'];
    	if ( empty($ids) ) {echo 0; return ;}

    	$creditTypeDao = M('credit_type');
    	//获取字段名
    	$typeName = $creditTypeDao->where("id in(".$ids.")")->select();

    	$_LOG['uid'] = $this->mid;
    	$_LOG['type'] = '2';
    	$data[] = L("global")."-".L("creditConfig")."-".L("creditType");//'全局 - 积分配置 - 积分类型 ';
    	//$data[] = $typeName;
    	$_LOG['data'] = serialize($data);
    	$_LOG['ctime'] = time();
    	M('AdminLog')->add($_LOG);

    	//清除type信息和对应字段
    	$res = $creditTypeDao->where("id in(".$ids.")")->delete();
    	if ($res){
    		$db_prefix  = C('DB_PREFIX');
            $model = M('');
            foreach($typeName as $v){
                $setting = $model->query("ALTER TABLE {$db_prefix}credit_setting DROP {$v['name']};");
                $user    = $model->query("ALTER TABLE {$db_prefix}credit_user DROP {$v['name']};");
            }
    		F('_service_credit_type', null);// 清缓存
    		echo 1;
    	}else{
    		echo 0;
    	}
    }

    /**
     * 系统配置 - 设置用户积分
     * Create Data <2013-05-02>
     */
    public function creditUser() {
        $creditType = M('credit_type')->order('id ASC')->select();
        $this->assign('creditType',$creditType);
        $userGroup=model('UserGroup')->order('user_group_id ASC')->select();
        $this->assign('grounlist',$userGroup);
        $this->display();
    }

    /**
     * 系统配置 - 设置用户积分-保存
     * Create Data <2013-05-02>
     */
    public function doCreditUser(){
    	set_time_limit(0);
    	//查询用户ID
    	$_POST['uId'] && $map['uid'] = array('in',explode(',',$_POST['uId']));
    	$_POST['gId']!='all' && $map['admin_level'] = intval($_POST['gId']);
    	$_POST['active']!='all' && $map['is_active'] = intval($_POST['active']);
    	$user = model('User')->where($map)->field('uid')->select();
    	if($user == false){
    		$this->error(L("noUser"));//人员不存在
    	}
    	//组装积分规则
    	$creditTypeDao = M('credit_type');
    	$creditType = $creditTypeDao->select();
    	$update_filed="";
    	foreach($creditType as $v){
    		if($_POST[$v['name']].trim()!="")
    		{
    			if(!is_numeric($_POST[$v['name']]))
    				$this->error($v['alias'].L("mstIsNumber"));//的值必须为数字！
	    		$action[$v['name']] = intval($_POST[$v['name']]);
	    		$update_filed=$update_filed." ".$v['name']."=ifnull(".$v['name'].",0)+(".$_POST[$v['name']]."),";
    		}
    	}
    	$update_filed	=	rtrim($update_filed,',');
    	$db_prefix  = C('DB_PREFIX');
    	$creditUser = M('credit_user');
    		foreach($user as $v){
    			$list = $creditUser->where("uid=".$v['uid'])->select();
    			if(count($list)>0)
    			{
    				if($_POST['action'] == 'set')//积分修改为
    				{
    					$res = $creditUser->where('uid='.$v['uid'])->setField($action);
    					if(!$res)$this->error(L('saveFails'));//保存失败
    				}else //增减积分
    				{
    					$upd_sql	=	"UPDATE ".$db_prefix."credit_user SET ".$update_filed;
    					$upd_sql=$upd_sql." where uid=".$v['uid'];
   						$res	=$creditUser->query($upd_sql);
   						if(count($res)!=0)$this->error(L('saveFails'));//保存失败
    				}
    			}else
    			{
    				$value= $action;
    				$value["uid"] = $v['uid'];
    				$res = $creditUser->data($value)->add();
    				if(!$res)$this->error(L('saveFails'));//保存失败
    			}
    		}

    	$this->assign('jumpUrl', URL('admin/Global/creditUser'));
    	$_LOG['type'] =($_POST['action'] == 'set') ? '3' : '1';
    	$_LOG['uid'] = $this->mid;
    	if( $_POST['action'] == 'set' ){
    		$data[] = L("creditUserSet");//'全局 - 积分配置 - 设置用户积分 - 积分修改操作 ';
    	}else{
    		$data[] = L("creditUserAdd");//'全局 - 积分配置 - 设置用户积分 - 积分增减操作 ';
    	}
    	$data['1'] = $action;
    	$data['1']['uid'] = $_POST['uId'];
    	$data['1']['gId'] = $_POST['gId'];
    	$data['1']['active'] = $_POST['active'];
    	$data['1']['action'] = $_POST['action'];
    	$_LOG['data'] = serialize($data);
    	$_LOG['ctime'] = time();
    	M('AdminLog')->add($_LOG);

    	$this->success(L('saveSuccess'));//保存成功
    }

    /**
     * 系统配置 - 公告配置
     * Create Data <2013-05-02>
     */
    public function announcement() {
        $announcement = model('Data')->lget('announcement');
        $this->assign($announcement);
    	$this->display();
    }

    /**
     * 公告设置－保存
     * Create Data <2013-05-02>
     */
    public function doSetAnnouncement() {
    	if (empty($_POST)) {
    		$this->error(L('parameterError'));//参数错误
    	}
    	$LOG['uid'] = $this->mid;
    	$LOG['type'] = '3';
    	$data[] = L("global")."-".L("announcementConfig");//'全局配置 - 公告设置 ';
    	$data[] = model('Data')->lget('announcement');
    	$data[] = $_POST;
    	$LOG['data'] = serialize($data);
    	$LOG['ctime'] = time();
    	M('AdminLog')->add($LOG);
    	$result = model('Data')->lput('announcement', $_POST);
    	if($result) {
    		$this->success(L('saveSuccess'));//保存成功
    	} else {
    		$this->error(L('saveFails'));//保存失败
    	}
    }

    /**
     * 系统配置 - 邮件配置
     * Create Data <2013-05-02>
     */
    public function email(){
    	if($_POST){
            $_LOG['uid'] = $this->mid;
            $_LOG['type'] = '3';
            $data[] = L("global")."-".L("emailConfig");//'系统配置 - 邮件配置 ';
            $data[] = model('Data')->lget('email');
            if( $_POST['__hash__'] )unset( $_POST['__hash__'] );
            $data[] = $_POST;
            $_LOG['data'] = serialize($data);
            $_LOG['ctime'] = time();
            M('AdminLog')->add($_LOG);

            unset($_POST['__hash__']);
    		$result = model('Data')->lput('email', $_POST);
            if($result) {
            	$this->success(L('saveSuccess'));//保存成功
            } else {
            	$this->error(L('saveFails'));//保存失败
            }

        }else{
            $data = model('Data')->lget('email');
            $this->assign($data);
            $this->display();
        }
    }

    /**
     * 发送测试邮件
     * Create Data <2013-05-02>
     */
    public function testSendEmail() {
    	$email_to=$_POST['testSendEmailTo'];
    	$data = model('Data')->lget('email');
    	$mailAddress = $data['email_host'];
    	$account = $data['email_account'];
    	$pass = $data['email_password'];
    	$sendName = $data['email_sender_name'];
    	$loginName = $data['email_loginName'];
    	$port = $data['email_port'];
    	$sl = $data['email_ssl_encrypt'];
    	$subject = '这是一封测试邮件';
    	$content = "这是一封来自'".SITE_URL."'的测试邮件，您能收到这封邮件表明邮件服务器已配置正确。<br />
					如果您不清楚这封邮件的来由，请删除，为给您带来的不便表示歉意";

    	$ret=common('Email')->SendMail($email_to,$content,$subject);
    	if($ret){
    		echo $ret;
    		exit;
    	}
    	echo 1;
    }

    /**
     * 系统配置 - 上传配置
     * Create Data <2013-05-02>
     */
    public function attachconfig() {
        $data = model('Data')->lget('attach');
        $this->assign($data);
        $this->display();
    }

    /**
     * 上传配置 - 空间附件
     * Create Data <2013-05-02>
     */
    public function zone() {
        $data = model('Data')->lget('attach');
        $this->assign($data);
        $this->display();
    }

    /**
     * 上传配置 - 水印设置
     * Create Data <2013-05-02>
     */
    public function water() {
        $data = model('Data')->lget('attach');
        $this->assign($data);
        $this->display();
    }

    /**
     * 又拍云配置
     */
    public function config() {
    	if($_POST) {
    		try {
    			$configname = $_POST['configname'];
    			$filename = SITE_PATH . '/apps/admin/Conf/'.$configname.'.php';
    			file_exists($filename) or touch($filename);
    			if($_POST['__hash__']) unset($_POST['__hash__']);
    			if($_POST['configname']) unset($_POST['configname']);
    			//$return = var_export($_POST, TRUE);
    			$result = model('Data')->lput( $configname, $_POST);
//     			if ($return) {
//     				file_put_contents($filename, "<?php \r\n return " . $return . ";");
//     			}
    			$this->success('配置成功',URL('admin/Global/config',array('configname'=>$configname)));
    		} catch (Exception $e) {
    			//$this->error("请检查文件{$filename}是否有读写权限");
    		}
    	} else {
    		$configname = empty($_GET['configname'])?'yun':$_GET['configname'];
    	//	$config = include SITE_PATH . '/apps/admin/Conf/'.$configname.'.php';
//     		if (!$config) {
//     			$config = array();
//     		}
    		$config = model('Data')->lget($configname);
    		$this->assign("config", $config);
    		$this->display($configname.'Config');
    	}
    }

    /**
     * 更新上传配置
     * Create Data <2013-05-02>
     */
    public function doSetAttach() {
    	if (empty($_POST)) {
    		$this->error(L('parameterError'));//参数错误
    	}
    	$LOG['uid'] = $this->mid;
    	$LOG['type'] = '3';
    	$data[] = L("global")."-".L("attachConfig"); //'全局 - 附件配置 ';
    	$data[] = model('Data')->lget('attach');
    	$data[] = $_POST;
    	$LOG['data'] = serialize($data);
    	$LOG['ctime'] = time();
    	M('AdminLog')->add($LOG);
    	$result = model('Data')->lput('attach', $_POST);
    	if($result) {
    		$this->success(L('saveSuccess'));//保存成功
    	} else {
    		$this->error(L('saveFails'));//保存失败
    	}
    }

    /**
     * 系统配置 - 文章配置
     * Create Data <2013-05-02>
     */
    public function document() {
    	$field="document_id,title,content,is_active,is_on_footer,mtime,ctime,last_editor_id,author_id,display_order ";
    	$data = M('Document')->order('`display_order` ASC,`document_id` ASC')->field($field)->select();
        for($j=0;$j<count($data);$j++){
        	$data[$j]["author"]=($this->_getUserName($data[$j]['author_id']));
        	$data[$j]["last_editor"]=($this->_getUserName($data[$j]['last_editor_id']));
        }
        $this->assign('list', $data);
        $this->display();
    }

    /**
     * 获取用户名
     * @param unknown_type $uid
     * @return string
     */
    private function _getUserName($uid){
    	$list = model('User')->where("uid=".$uid)->field("uname")->select();
    	if(count($list)>0)
    		return $list[0]["uname"];
    	else
    		return "";
    }

    /**
     * 添加文章
     * Create Data <2013-05-02>
     */
    public function addDocument() {
        $this->assign('type', 'add');
        $this->display('editDocument');
    }

    /**
     * 编辑文章
     * Create Data <2013-05-02>
     */
    public function editDocument() {
        $map['document_id'] = intval($_GET['id']);
        $document = M('document')->where($map)->find();
        if ( empty($document) )
            $this->error(L('docNotExist'));//该文章不存在
        $this->assign($document);

        $this->assign('type', 'edit');
        $this->display();
    }

    /**
     * 保存文章
     * Create Data <2013-05-02>
     */
    public function doEditDocument(){
        if (($_POST['document_id'] = intval($_POST['document_id'])) <= 0)
            unset($_POST['document_id']);

        // 格式化数据
        $type=$_POST['type'];
        $value['title']         = $_POST['title'];
        $value['is_active']     = intval($_POST['is_active']);
        $value['is_on_footer']  = intval($_POST['is_on_footer']);
        $value['last_editor_id']= ($this->mid=="")?"1": $this->mid;
        $value['mtime']         = time();
        if (preg_match('/^\s*((?:https?|ftp):\/\/(?:www\.)?(?:[a-zA-Z0-9][a-zA-Z0-9\-]*\.)?[a-zA-Z0-9][a-zA-Z0-9\-]*(?:\.[a-zA-Z]+)+(?:\:[0-9]*)?(?:\/[^\x{2e80}-\x{9fff}\s<\'\"“”‘’]*)?)\s*$/u', strip_tags(html_entity_decode($_POST['content'], ENT_QUOTES, 'UTF-8')), $url)
            || preg_match('/^\s*((?:mailto):\/\/[a-zA-Z0-9_]+@[a-zA-Z0-9][a-zA-Z0-9\.]*[a-zA-Z0-9])\s*$/u', strip_tags(html_entity_decode($_POST['content'], ENT_QUOTES, 'UTF-8')), $url)) {
            $value['content'] = common('Html')->safeHtml($url[1]);
        } else {
            $value['content'] = $_POST['content'];
        }

        $document=M('document');
		//检查文章标题是否已经存在
        $list = $document->where("title='".$value['title']."' AND document_id<>".intval($_POST['document_id']))->select();
        if(count($list)>0){
        	echo 1;//标题已经存在
        	exit;
        }
        $_LOG['uid'] = $this->mid;
        $_LOG['type'] = ($type=="edit") ? '3' : '1';
        $data[] = L("global")."-".L("documentConfig");//'全局 - 文章配置 ';
        if($type=="edit")
        	$data[] =  $document->where( array( 'document_id'=>intval($_POST['document_id']) ) )->select();
        if( $_POST['__hash__'] ) unset( $_POST['__hash__'] );
        $data[] = $value;
        $_LOG['data'] = serialize($data);
        $_LOG['ctime'] = time();
        M('AdminLog')->add($_LOG);
        // 提交
        if ($type=="add"){
            // 新建文章
            $value['author_id'] = ($this->mid=="")?"1": $this->mid;
            $value['ctime']     = time();//$_POST['mtime'];
        	//取得最大文章代码
        	$document_id = $document->max('document_id');
        	$value['document_id']=$document_id+1;
        	// 为排序方便, 新建时, 将display_order设置为document_id
        	$value['display_order']=$document_id+1;
        	$res = $document->data($value)->add();
        }
        else{
        	$value['document_id']=$_POST['document_id'];
        	$res = $document->save($value);
        }
        // 清理缓存
        F('_action_footer_document', null);
        if ($res) {
           echo 2;//保存成功
        } else {
           echo 0;//保存失败
        }
    }

    /**
     * 删除文章
     * Create Data <2013-05-02>
     */
    public function doDeleteDocument(){
        if (empty($_POST['ids'])){
            echo 0;
            exit ;
        }

        $_LOG['uid'] = $this->mid;
        $_LOG['type'] = '2';
        $data[] = L("global")."-".L("documentConfig");//'全局 - 文章配置 ';
        $data[] = model('Data')->lget('platform');
        if( $_POST['__hash__'] )unset( $_POST['__hash__'] );
        $data[] = $_POST;
        $_LOG['data'] = serialize($data);
        $_LOG['ctime'] = time();
        M('AdminLog')->add($_LOG);

        echo M('document')->where('document_id in('.$_POST['ids'].')')->delete() ? '1' : '0';
        // 清理缓存
        F('_action_footer_document', null);
    }

    /**
     * 文章排序
     * Create Data <2013-05-02>
     */
    public function doDocumentOrder() {
        $_POST['document_id']   = intval($_POST['document_id']);
        $_POST['baseid']        = intval($_POST['baseid']);
        if ( $_POST['document_id'] <= 0 || $_POST['baseid'] <= 0 ) {
            echo 0;
            exit;
        }

        // 获取详情
        $map="document_id in(".$_POST['document_id'].",". $_POST['baseid'].")";
        $res = M('document')->where($map)->field('document_id,display_order')->select();
        if ( count($res) < 2 ) {
            echo 0;
            exit;
        }

        //转为结果集为array('id'=>'order')的格式
        foreach($res as $v) {
            $order[$v['document_id']] = intval($v['display_order']);
        }
        unset($res);

        //交换order值
        $res =         M('document')->where('`document_id`=' . $_POST['document_id'])->setField(  'display_order', $order[$_POST['baseid']] );
        $res = $res && M('document')->where('`document_id`=' . $_POST['baseid'])->setField( 'display_order', $order[$_POST['document_id']]  );

        if ($res) {
        	// 清理缓存
        	F('_action_footer_document', null);
        	echo 1;
        } else {
        	echo 0;
        }

    }

    /**
     * 系统配置 - 审核配置
     * Create Data <2013-05-02>
     */
    public function audit(){
        $audit = model('Data')->lget('audit');
        $this->assign($audit);
    	$this->display();
    }
	//审核配置－保存
    public function doSetAudit() {
    	if (empty($_POST)) {
    		$this->error(L('parameterError'));//参数错误
    	}
    	$LOG['uid'] = $this->mid;
    	$LOG['type'] = '3';
    	$data[] = L("global")."-".L("auditConfig");//'全局配置 - 审核配置 ';
    	$data[] = model('Data')->lget('audit');
    	$data[] = $_POST;
    	$LOG['data'] = serialize($data);
    	$LOG['ctime'] = time();
    	M('AdminLog')->add($LOG);
    	$result = model('Data')->lput('audit', $_POST);
    	if($result) {
    		$this->success(L('saveSuccess'));//保存成功
    	} else {
    		$this->error(L('saveFails'));//保存失败
    	}
    }

    /**
     * 系统配置 - 微博配置
     * Create Data <2013-05-02>
     */
    public function weibo() {
        $weibo = model('Data')->lget('weibo');
        $this->assign($weibo);
    	$this->display();
    }

    /**
     * 微博配置－保存
     * Create Data <2013-05-02>
     */
    public function doSetWeibo() {
    	if (empty($_POST)) {
    		$this->error(L('parameterError'));//参数错误
    	}
        //验证数字参数
        if( intval($_POST['max_post_time'])<0
             || intval($_POST['max_refresh_time'])<0
             || intval($_POST['max_following'])<0
             || intval($_POST['max_search_time'])<0
        ){
            $this->error(L('numMustGreaterThan0'));//数字变量的值必须大于等于0
        }
        $_POST['max_post_time'] = intval($_POST['max_post_time']);
        $_POST['max_refresh_time'] = intval($_POST['max_refresh_time']);
        $_POST['max_following'] = intval($_POST['max_following']);
        $_POST['max_search_time'] = intval($_POST['max_search_time']);

        if (intval($_POST['length']) <= 0) {
            $this->error(L('lmtGreaterThan0'));//全站微博、评论字数限制的值必须大于0
        }

        //保存LOGO
        if (!empty ($_FILES['site_logo']['name'][0])) {
        	import("ORG.Net.UploadFile");
			$upload = new UploadFile(); // 实例化上传类
			$upload->maxSize = 10240; // 设置附件上传大小:10kb
			$upload->allowExts = array (
					'jpg',
					'gif',
					'png',
					'jpeg'
			); // 设置附件上传类型
			$upload->savePath = './data/uploads/image/'; // 设置附件上传目录
			$upload->saveRule = 'uniqid'; //设置上传文件规则
			if (!$upload->upload()) { // 上传错误提示错误信息
				$this->error($upload->getErrorMsg());
			} else { // 上传成功 获取上传文件信息
				$info = $upload->getUploadFileInfo();
				$_POST['site_logo'] = __ROOT__ . '/data/uploads/image/' . $info[0]["savename"];
			}
        }

    	$LOG['uid'] = $this->mid;
    	$LOG['type'] = '3';
    	$data[] = L("global")."-".L("weiboConfig");//'全局配置 - 微博配置 ';
    	$data[] = model('Data')->lget('weibo');
    	$data[] = $_POST;
    	$LOG['data'] = serialize($data);
    	$LOG['ctime'] = time();
    	M('AdminLog')->add($LOG);
    	$result = model('Data')->lput('weibo', $_POST);
    	if($result) {
    		$this->success(L('saveSuccess'));//保存成功
    	} else {
    		$this->error(L('saveFails'));//保存失败
    	}
    }

    /**
     * 系统配置 - 地区配置
     * Create Data <2013-05-02>
     */
    public function area() {
    	$data = M('area')->order('`area_id` ASC')->where('pid=0')->select();
		$this->assign('area', $data);
		$this->assign('pid', "");
		$this->display();
    }

    /**
     * 系统配置 - 地区配置查询
     * Create Data <2013-05-02>
     */
    public function doQryArea(){
    	$pid=$_GET['pid'];
    	if($pid=="")$pid=0;
    	$data = M('area')->order('`area_id` ASC')->where('pid='.$pid)->select();
		$this->assign('area', $data);

		$data = M('area')->where('area_id='.$pid)->select();
		if(count($data)>0)
			$this->assign('pid', $data[0]["pid"]);
		else
			$this->assign('pid', "");
    	$this->display("area");

    }

    /**
     * 系统配置 - 地区配置保存
     * Create Data <2013-05-02>
     */
    function doBackArea(){
    	$province_id=$_GET['province'];
    	$city_id=$_GET['city'];
    	$pid=$city_id;
    	if($pid=="")$pid=$province_id;
    	$data = M('area')->order('`area_id` ASC')->where('pid='.$pid)->select();
		$this->assign('area', $data);
		$data = M('area')->where('pid=0')->select();
		$this->assign('province', $data);
    	$data = M('area')->where('pid='.$province_id)->select();
    	$this->assign('city', $data);
		$this->assign('province_id', $province_id);
		$this->assign('city_id', $city_id);
    	$this->display("area");
    }

    /**
     * 查询 by pid,用於AJAX
     * Create Data <2013-05-02>
     */
    public function ajaxQryArea(){
    	$pid = $_POST['pid'];
    	$data = M('area')->where('pid='.$pid)->select();
    	echo "<?xml version='1.0' ?><XMLDATA>";
    	FOR ($i = 0; $i <count($data); $i++)
    	{
    		echo "<Item><area_id>".$data[$i]['area_id']."</area_id>";
    		echo "<title>".$data[$i]['title']."</title></Item>";
    	}
    	echo "</XMLDATA>";
    }

    /**
     * 查询 by pid,用於AJAX
     * Create Data <2013-05-02>
     */
    public function ajaxQryAreaCount(){
    	$pid = $_POST['pid'];
    	$data = M('area')->where('pid='.$pid)->select();
    	echo count($data);
    }

    /**
     * 系统配置 - 地区添加
     * Create Data <2013-05-02>
     */
    public function addArea() {
    	$this->assign('pid', $_GET['pid']);
    	$data = M('area')->where('pid=0')->select();
    	$this->assign('province', $data);
    	$this->assign('province_id', 0);
    	$this->assign('city_id', "");
    	$this->assign('type', 'add');
    	$this->display('editArea');
    }

    /**
     * 系统配置 - 地区编辑
     * Create Data <2013-05-02>
     */
    public function editArea() {
    	$_GET['area_id'] = intval($_GET['area_id']);
    	$pid = intval($_GET['pid']);
    	$data = M('area')->where('area_id='.$_GET['area_id'])->select();
    	$this->assign('title', $data[0]['title']);
    	$this->assign('pid', $_GET['pid']);
    	$this->assign('area_id', $_GET['area_id']);
    	//取得省份清單
    	$data = M('area')->where('pid=0')->select();
    	$this->assign('province', $data);
    	$this->assign('province_id', $pid);
    	$this->assign('city_id', "");
    	$this->assign('pid', $pid);
    	$province_id=$pid;
    	$city_id="";
    	if($pid !=0){
    		$data = M('area')->where('area_id='.$pid)->select();
    		$newPid=$data[0]["pid"];
    		if($newPid !=0){
    			$city_id=$pid;
    			$province_id=$newPid;
	    		$data = M('area')->where('pid='.$newPid)->select();
	    		$this->assign('city', $data);
    		}
    	}
    	$this->assign('province_id', $province_id);
    	$this->assign('city_id', $city_id);
    	$this->assign('type', 'edit');
    	$this->display();
    }

    /**
     * 系统配置 - 地区添加
     * Create Data <2013-05-02>
     */
    public function doAddArea() {
		$_POST['title']	= $_POST['title'];
		$_POST['pid']	= intval($_POST['pid']);
		if (empty($_POST['title'])) {
			echo 0;
			return ;
		}

		$_LOG['uid'] = $this->mid;
		$_LOG['type'] = '1';
		$data[] = L("global")."-".L("areaConfig");//'全局配置 - 地区管理';
		$data[] = $_POST;
		$_LOG['data'] = serialize($data);
		$_LOG['ctime'] = time();
		M('AdminLog')->add($_LOG);

		F('Cache_PostArea',null);
		$area=M('area');// 实例化area对象
		//取得最大地区代码
		$area_id = $area->max('area_id');
		$area_id=$area_id+1;
    	//保存
    	$value["title"] = $_POST['title'];
    	$value["pid"] = $_POST['pid'];
    	$value["area_id"] = $area_id;
		$res = $area->data($value)->add();
		echo ($res) ? $res : '0';
    }

    /**
     * 系统配置 - 地区设置保存
     * Create Data <2013-05-02>
     */
    public function doEditArea() {
    	$_POST['title']		= $_POST['title'];
    	$_POST['area_id']	= intval($_POST['area_id']);
    	$_POST['pid']	= intval($_POST['pid']);
    	if (empty($_POST['title'])) {
    		//echo 0;
    		return ;
    	}
    	$area=M('area');// 实例化area对象
    	$_LOG['uid'] = $this->mid;
    	$_LOG['type'] = '3';
    	$data[] =  L("global")."-".L("areaConfig");//'全局配置 - 地区管理';
    	$data[] =  $area->where( array( 'area_id'=>intval($_POST['area_id']) ) )->select();
    	$data[] = $_POST;
    	$data['2']['pid'] = $data['1']['pid'];
    	$_LOG['data'] = serialize($data);
    	$_LOG['ctime'] = time();
    	M('AdminLog')->add($_LOG);

    	F('Cache_PostArea',null);
    	//保存修改
    	$value["title"] = $_POST['title'];
    	$value["pid"] = $_POST['pid'];

    	$res = $area->where('area_id='.$_POST['area_id'])->setField($value); // 根据条件保存修改的数据

    	if($res) echo 1;
    	else	 echo 0;
    }

    /**
     * 系统配置 - 地区删除
     * Create Data <2013-05-02>
     */
    public function doDeleteArea() {
    	$_POST['ids']	= $_POST['ids'];
    	if (empty($_POST['ids'])) {
    		echo 0;
    		return ;
    	}
    	$area = M('area');
    	$_LOG['uid'] = $this->mid;
    	$_LOG['type'] = '2';
    	$data[] =  L("global")."-".L("areaConfig");//'全局配置 - 地区管理';
    	$data[] =  $area->where( $map )->select();
    	$_LOG['data'] = serialize($data);
    	$_LOG['ctime'] = time();
    	M('AdminLog')->add($_LOG);

    	F('Cache_PostArea',null);
    	echo $area->where("area_id in(".$_POST['ids'].")")->delete() ? "1" : "0";
    }

    /**
     * 系统配置-导航配置
     */
    public function nav() {
    	$list = M("nav") -> select();
    	$navlist = array();
    	foreach ($list as $k => $v){
    		$list[$k]['url'] = empty($v['url']) ? 'javascript:;' : str_replace('{website}', SITE_URL, $v['url']);
    		if(intval($v['pid']) == 0){
    			$navlist[intval($v['id'])] = $list[$k];
    		}
    	}
    	foreach ($list as $k => $v){
    		if(intval($v['pid']) > 0){
    			$navlist[intval($v['pid'])]['child'][] = $v;
    		}
    	}
    	$this->assign("site_top_nav",$navlist);
    	$this->display("nav");
    }

    /**
     * 系统配置-添加导航
     */
    public function addNav() {
    	if(isset($_GET['id'])){
    		$data = M("nav") -> where("id=".$_GET['id']) -> find();
    		$data["pid"] = intval($data['pid']);
    		$this->assign($data);
    		$this->assign("type","edit");
    	}else if(isset($_GET['pid'])){
    		$this->assign("pid",$_GET['pid']);
    	}
    	$this->display();
    }

    /**
     * 系统配置-添加导航
     */
    public function doaddNav() {
    	if(!empty($_POST['id'])){
    		$data["id"] = intval($_POST["id"]);
    		$data["name"] = $_POST["name"];
    		$data["url"] = $_POST["url"];
    		$data["order_sort"] = intval($_POST["order_sort"]);
    		$data["pid"] = intval($_POST["pid"]);
    		$data["status"] = intval($_POST["status"]);
    		$data["no_login_show"] = intval($_POST["no_login_show"]);
    		$res = M("nav") -> save($data);
    	}else{
    		$data["name"] = $_POST["name"];
    		$data["url"] = $_POST["url"];
    		$data["order_sort"] = intval($_POST["order_sort"]);
    		$data["pid"] = intval($_POST["pid"]);
    		$data["status"] = intval($_POST["status"]);
    		$data["no_login_show"] = intval($_POST["no_login_show"]);
    		$res = M("nav") -> add($_POST);
    	}
    	if($res !== false){
    		$this->nav();
    	}else{
    		$this->error("操作失败！");
    	}
    }

    /**
     * 系统配置-删除导航
     */
    public function deleteNav(){
    	if(!empty($_POST['ids'])){
    		$res = M("nav") -> where("id in(".$_POST['ids'].")") -> delete();
    	}
    	if($res !== false){
    		echo 1;
    	}else{
    		echo 0;
    	}
    }

    /**
     * 系统配置-搜索引擎配置
     */
    public function robots(){
    	$this->analyseRobots();
    	$this->display();
    }

    /**
     * 更新robots.txt文件内容
     */
    public function updateRobots(){    	
    	try {
	    	$filename = SITE_PATH . '/robots.txt';
	    	file_exists($filename) or touch($filename);
	    	file_put_contents($filename,$_POST['robotstext']);
    	} catch (Exception $e) {
    		$this->error("操作失败！");
    	}
    	$this->assign("robotstext",$_POST['robotstext']);
    	$this->assign('jumpUrl', URL('admin/Global/robots'));
    	$this->success(L('saveSuccess'));//保存成功
    }

    /**
     * 分析搜索引擎收录的链接
     */
    public function analyseRobots(){
    	$urllist = array();
    	$robotsArr = "User-Agent: *"."\n".
    			"Disallow: /api/"."\n".
    			"Disallow: /apps/"."\n".
    			"Disallow: /config/"."\n".
    			"Disallow: /install/"."\n".
    			"Disallow: /Public/"."\n".
    			"Disallow: /template/"."\n".
    			"Disallow: /ocean/"."\n".
    			"Disallow: /login?type=*"."\n".
    			"Disallow: /index.php?s=*"."\n".
    			"Disallow: /index.php?app=*"."\n";
    	
    	$robotsurl = 'http://' . $_SERVER ['SERVER_NAME'] . '/robots.txt';
    	$robotshtml = @file_get_contents($robotsurl);
    	if($robotshtml===$robotsArr){
	    	$urllist['baidu'] =  $this->baidu();
	    	$urllist['soso'] =  $this->soso();
	    	$urllist['so360'] =  $this->so360();
	    	if(!empty($urllist)){
	    		foreach ($urllist as $k => $v){
	    			foreach ($v as $k1 => $v1){
	    				$res = $this->analyseUrl($v1);
	    				if ($res === false){
	    					unset($urllist[$k][$k1]);
	    					continue;
	    				}
	    				if (!strpos($robotsArr,$res)){
	    					$robotsArr=$robotsArr.$res."\n";
	    				}
	    			}
	    		}
	    	}
    	}else{
    		$robotsArr=$robotshtml;
    	}
    	$this->assign("robotstext",$robotsArr);
    }

    private function analyseUrl($url){
    	$SITE_URL = $_SERVER ['SERVER_NAME'];
    	$res = false;
    	if (strpos($url,$SITE_URL.'/api/') !== false){
    		$res = 'Disallow: /api/';
    	}else if (strpos($url,$SITE_URL.'/apps/') !== false){
    		$res = 'Disallow: /apps/';
    	}else if (strpos($url,$SITE_URL.'/config/') !== false){
    		$res = 'Disallow: /config/';
    	}else if (strpos($url,$SITE_URL.'/install/') !== false){
    		$res = 'Disallow: /install/';
    	}else if (strpos($url,$SITE_URL.'/Public/') !== false){
    		$res = 'Disallow: /Public/';
    	}else if (strpos($url,$SITE_URL.'/template/') !== false){
    		$res = 'Disallow: /template/';
    	}else if (strpos($url,$SITE_URL.'/ocean/') !== false){
    		$res = 'Disallow: /ocean/';
    	}else if (strpos($url,$SITE_URL.'/login?type=') !== false){
    		$res = 'Disallow: /login?type=*';
    	}else if (strpos($url,$SITE_URL.'/index.php?s=') !== false){
    		$res = 'Disallow: /index.php?s=*';
    	}else if (strpos($url,$SITE_URL.'/index.php?app=') !== false){
    		$res = 'Disallow: /index.php?app=*';
    	}else if (strpos($url,$SITE_URL.'.js') !== false){
    		$res = 'Disallow: /*.js$';
    	}else if (strpos($url,$SITE_URL.'.css') !== false){
    		$res = 'Disallow: /*.css$';
    	}
    	return $res;
    }


    /**
     * 获取360收录的链接
     * @return unknown
     */
    public function so360(){
    	$domain = $_SERVER ['SERVER_NAME'];
    	$site_url = 'http://so.360.cn/s?q=site%3A';
    	$all = $site_url.$domain;
    	$html = @file_get_contents($all);

    	preg_match_all ("/<h3.*>\s+<a\s+.*href=[\"|']?([^\"'>\s]+)[\"|']?/", $html, $matches);

    	return $matches[1];
    }

    /**
     * 获取soso收录的链接
     * @return unknown
     */
    public function soso(){
    	$domain = $_SERVER ['SERVER_NAME'];
    	$site_url = 'http://www.soso.com/q?query=site%3A';
    	$all = $site_url.$domain;
    	$html = @file_get_contents($all);

    	preg_match_all ("/<h3.*>.*<a.+href=[\"|']?([^\"'>\s]+)[\"|']?>.+<\/h3>/", $html, $matches);

    	return $matches[1];
    }

    /**
     * 获取百度收录的链接
     * @return Ambigous <>
     */
    public function baidu(){
    	$domain = $_SERVER ['SERVER_NAME'];
    	$site_url = 'http://www.baidu.com/s?wd=site%3A';
    	$all = $site_url.$domain;
    	$html = @file_get_contents($all);

    	preg_match_all ("/data-tools=\".*,url:[\"|']?([^\"'>\s]+)[\"|']?/", $html, $matches);

    	foreach ($matches[1] as $k => $v){
    		$matches[1][$k] = $this->getBaiduRealUrl($v);
    	}

    	return $matches[1];
    }

    /**
     * 获取百度搜索引擎收录的真实url
     * @param unknown_type $url
     * @return unknown
     */
    private function getBaiduRealUrl($url){
    	$header=get_headers($url,1);
    	if (strpos($header[0],'301')||strpos($header[0],'302')){
    		if(is_array($header['Location'])){
    			return $header['Location'][count($header['Location'])-1];
    		}else{
    			return $header['Location'];
    		}
    	}else{
    		return $url;
    	}
    }

    /**
     * 设置图片附近功能是否开启
     */
    public function imagenearConfig(){
    	$weiboimageConfig = include SITE_PATH . '/apps/weibo/Conf/weiboimageConfig.php';
    	$this->assign("opennosql",$weiboimageConfig['opennosql']);
    	$this->display();
    }

    /**
     * 图片附件功能设置
     */
    public function doimagenearConfig(){
    	if(empty($_POST)){
    		$this->error("请选择是否开启图片附近功能");
    	}
    	try {
    		$filename = SITE_PATH . '/apps/weibo/Conf/weiboimageConfig.php';
    		file_exists($filename) or touch($filename);
    		if($_POST['__hash__']) unset($_POST['__hash__']);
    		$return = var_export($_POST, TRUE);
    		if ($return) {
    			file_put_contents($filename, "<?php \r\n return " . $return . ";");
    		}
    		$this->success('配置成功');
    	} catch (Exception $e) {
    		$this->error("请检查文件weiboimageConfig.php是否有读写权限");
    	}
    }
}
?>
